package com.sunshine.user.service.impl;

import com.sunshine.user.dto.UserRegisterDTO;
import com.sunshine.user.entity.Users;
import com.sunshine.user.mapper.UsersDao;
import com.sunshine.user.service.UsersService;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import sunshine.commcon.util.JwtUtil;
import sunshine.commcon.util.entity.Result;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户基本信息表(Users)表服务实现类
 *
 * @author makejava
 * @since 2025-09-14 17:25:41
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Resource
    private UsersDao usersDao;
    
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Result<Boolean> register(UserRegisterDTO userRegisterDTO) {
        try {
            UserRegisterDTO users = new UserRegisterDTO();
            //查看用户名是否已存在
            Users selectusers = usersDao.selectUser(userRegisterDTO.getUsername());
            if (selectusers != null) {
                return Result.fail("用户名已经存在");
            }
            //插入用户
            Users users1 = new Users();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            users1.setPassword(bCryptPasswordEncoder.encode(userRegisterDTO.getPassword()));
            users1.setUsername(userRegisterDTO.getUsername());
            users1.setCreatedAt(new Date()); // 添加创建时间
            usersDao.insert(users1);
            return Result.ok(true);
        } catch (Exception e) {
            return Result.fail("系统异常");
        }


    }

    @Override
    public Result<Users> login( String username, String password) {
            Users users = new Users();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            //查找是否有该用户
            Users selectusers = usersDao.selectUser(username);
            if (selectusers != null) {
                //验证密码
                if (bCryptPasswordEncoder.matches(password, selectusers.getPassword())) {
                    String token = JwtUtil.createToken(selectusers.getUserId(), users.getUsername());
                    selectusers.setToken(token);
                    redissonClient.getBucket("user_token:" + selectusers.getUserId()).set(token, 24, TimeUnit.HOURS);
                    return Result.ok(selectusers);
                }

            }
            return Result.fail("用户名或密码错误");
    }


    @Override
    public Result<Boolean> updatePassword( UserRegisterDTO userRegisterDTO ) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 验证用户是否存在
        Users users = usersDao.selectUser(userRegisterDTO.getUsername());
        if (users == null) {
            return Result.fail("用户不存在");
        }
        
        // 验证旧密码是否正确
        if (!bCryptPasswordEncoder.matches(userRegisterDTO.getPassword(), users.getPassword())){
            return Result.fail("旧密码错误");
        }
        
        // 更新密码和更新时间
        Users updateUser = new Users();
        updateUser.setUsername(userRegisterDTO.getUsername());
        updateUser.setPassword(bCryptPasswordEncoder.encode(userRegisterDTO.getNewPassword()));
        updateUser.setUpdateTime(new Date());
        
        int result = usersDao.updatePassword(updateUser);
        if (result <= 0) {
            return Result.fail("密码更新失败");
        }
        
        // 清除Redis中的token，强制用户重新登录
        redissonClient.getBucket("user_token:" + users.getUserId()).delete();
        
        return Result.ok(true);
    }


}